import { Injectable } from '@nestjs/common';
import { Category } from './category.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { pagination } from '../utils/pagination';
// import { Bookmark } from '../bookmark.entity';
const {
  categoryNameExpire,
  categoryIDExpire,
  categoryErrExpire,
} = require('../provider/error');

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category) private category: Repository<Category>,
  ) {}

  async categoryList(params) {
    return await pagination(params, this.category, 'category');
  }

  createCategory(bodyData) {
    if (!bodyData || !bodyData.name || bodyData.name == '')
      return categoryNameExpire();
    this.category.save({
      name: bodyData.name,
      sort: bodyData.sort ? bodyData.sort : 1,
      create_time: new Date(),
      updated_time: new Date(),
    });
    return [];
  }

  async updatedCategory(bodyData) {
    if (!bodyData.id) return categoryIDExpire();
    if (!bodyData || !bodyData.name || bodyData.name == '')
      return categoryNameExpire();
    const res = await this.category.update(bodyData.id, {
      name: bodyData.name,
      sort: bodyData.sort ? bodyData.sort : 1,
      updated_time: new Date(),
    });
    if (res.affected !== 1) return categoryErrExpire();
    return [];
  }

  async delCategory(params) {
    // const findRes = await this.bookmark.findOne({
    //   where: { category_id: params.id },
    // });
    // if (findRes) return categoryDelBookmarkExpire();
    if (!params.id) return categoryIDExpire();
    const res = await this.category.delete(params.id);
    if (res.affected !== 1) return categoryErrExpire();
    return [];
  }

  async categorySelect() {
    const res = await this.category
      .createQueryBuilder('category')
      .addOrderBy('sort', 'DESC')
      .getMany();
    // const data = {};
    // res.forEach((t) => {
    //   data[t.id] = t.name;
    // });
    return res;
  }
}
